package com.cuitrip.business.user;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.model.ThirdAccount;
import com.cuitrip.business.login.proxy.ThirdAccountProxy;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.SpanUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.MessageUtils;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;

/**
 * 社交帐号绑定
 * Created by ak
 */
public class SocialBindActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final String USER_KEY = "user";

    @Bind(R.id.layout_wechat)
    ItemLayout wechatLayout;

    @Bind(R.id.layout_weibo)
    ItemLayout weiboLayout;

    @Bind(R.id.layout_facebook)
    ItemLayout facebookLayout;
    @Bind(R.id.layout_google)
    ItemLayout googleLayout;
    private CtUserInfo mUserInfo = null;
    private ApiProxy mApiProxy = new ApiProxy(this);

    private ThirdAccountProxy thirdAccountProxy = new ThirdAccountProxy();

    public void initView() {
        ButterKnife.bind(this);
        thirdAccountProxy.init(this);
        if (ThirdAccountProxy.isGoogleInstall(AppCoreRuntime.context)) {
            googleLayout.setVisibility(View.VISIBLE);
        } else {
            googleLayout.setVisibility(View.GONE);
        }
        if (ThirdAccountProxy.isWechatInstall(AppCoreRuntime.context)) {
            wechatLayout.setVisibility(View.VISIBLE);
        } else {
            wechatLayout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getIntent().hasExtra(USER_KEY)) {
            mUserInfo = (CtUserInfo) getIntent().getSerializableExtra(USER_KEY);
        } else {
            finish();
        }
        super.onCreate(savedInstanceState, R.layout.page_socail_account);

    }

    @Override
    public void initData() {
        refreshData();
    }

    @Override
    protected void onDestroy() {
        thirdAccountProxy.destroy();
        super.onDestroy();
    }

    private void refreshData() {
        SpannableStringBuilder wechatBuilder = new SpannableStringBuilder();
        if (mUserInfo.isWechatValidated()) {
            wechatBuilder.append(getString(R.string.value_connected));
            wechatBuilder.append(" ");
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), getString(R.string.wechat_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            wechatBuilder.append(spannableString);
        } else {
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getColor(R.color.ganshi_ded8d7), getString(R.string.wechat_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            wechatBuilder.append(spannableString);
        }
        wechatLayout.setmRightText(wechatBuilder);


        SpannableStringBuilder weiboBuilder = new SpannableStringBuilder();
        if (mUserInfo.isWeiboValidated()) {
            weiboBuilder.append(getString(R.string.value_connected));
            weiboBuilder.append(" ");
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), getString(R.string.weibo_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            weiboBuilder.append(spannableString);
        } else {
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getColor(R.color.ganshi_ded8d7), getString(R.string.weibo_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            weiboBuilder.append(spannableString);
        }
        weiboLayout.setmRightText(weiboBuilder);


        SpannableStringBuilder facebookBuilder = new SpannableStringBuilder();
        if (mUserInfo.isFacebookValidated()) {
            facebookBuilder.append(getString(R.string.value_connected));
            facebookBuilder.append(" ");
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), getString(R.string.facebook_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            facebookBuilder.append(spannableString);
        } else {
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getColor(R.color.ganshi_ded8d7), getString(R.string.facebook_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            facebookBuilder.append(spannableString);
        }
        facebookLayout.setmRightText(facebookBuilder);


        SpannableStringBuilder googleBuilder = new SpannableStringBuilder();
        if (mUserInfo.isGoogleValidated()) {
            googleBuilder.append(getString(R.string.value_connected));
            googleBuilder.append(" ");
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), getString(R.string.google_plus_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            googleBuilder.append(spannableString);
        } else {
            SpannableString spannableString = SpanUtil.getColorSpanString(ResourceUtil.getColor(R.color.ganshi_ded8d7), getString(R.string.google_plus_icon));
            SpanUtil.setSize(spannableString, 1.5f);
            googleBuilder.append(spannableString);
        }
        googleLayout.setmRightText(googleBuilder);

    }

    private ThirdAccountProxy.OnAuthListener onAuthListener = new ThirdAccountProxy.OnAuthListener() {
        @Override
        public void onComplete(ThirdAccount thirdAccount) {
            showLoading();
            UserBusiness.bindThirdAccount(mApiProxy, thirdAccount);
        }

        @Override
        public void onCancel() {

        }
    };

    private void unBindAccountConfirm(final int accountType) {
        final ChoiceDialog dialog = new ChoiceDialog();
        dialog.setDialogTitleVisibility(false);
        dialog.setDialogMessage(getString(R.string.operation_disconnect));
        dialog.setDialogCoupleStyleSetting(getString(R.string.operation_disconnect), getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
            @Override
            public boolean onPositiveButtonClick() {
                unBindAccount(accountType);
                dialog.dismiss();
                return true;
            }

            @Override
            public boolean onNegativeButtonClick() {
                dialog.dismiss();
                return true;
            }
        });
        showDialogFragment(dialog);
    }

    private void unBindAccount(int accountType) {
        showLoading();
        UserBusiness.unbindThirdAccount(mApiProxy, accountType);
    }

    @OnClick(R.id.layout_wechat)
    void onWechatAuth() {
        if (mUserInfo.isWechatValidated()) {
            unBindAccountConfirm(ThirdAccount.WE_CHAT);
        } else {
            thirdAccountProxy.authorizeThirdAccount(ThirdAccount.WE_CHAT,  onAuthListener);
        }
    }

    @OnClick(R.id.layout_weibo)
    void onWeiboAuth(){
        if(mUserInfo.isWeiboValidated()){
            unBindAccountConfirm(ThirdAccount.WEIBO);
        }else{
            thirdAccountProxy.authorizeThirdAccount(ThirdAccount.WEIBO,  onAuthListener);
        }
    }

    @OnClick(R.id.layout_facebook)
    void onFacebookAuth() {
        if (mUserInfo.isFacebookValidated()) {
            unBindAccountConfirm(ThirdAccount.FACEBOOK);
        } else {
            thirdAccountProxy.authorizeThirdAccount(ThirdAccount.FACEBOOK,  onAuthListener);
        }
    }

    @OnClick(R.id.layout_google)
    void onGoogleAuth() {
        if (mUserInfo.isGoogleValidated()) {
            unBindAccountConfirm(ThirdAccount.GOOGLE);
        } else {
            thirdAccountProxy.authorizeThirdAccount(ThirdAccount.GOOGLE,  onAuthListener);
        }
    }

    private void handleBindAccountResult(CtApiResponse response) {
        hideLoading();
        if (response.isResponseNormal()) {
            if (response.result instanceof CtUserInfo) {
                CtUserInfo userInfo = (CtUserInfo) response.result;
                LoginInstance.getInstance().updateProfile(AppCoreRuntime.context, userInfo, false);
                mUserInfo = userInfo;
                refreshData();
            }
        } else {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
    }

    private void handleUnBindAccountResult(CtApiResponse response) {
        hideLoading();
        if (response.isResponseNormal() && response.result instanceof CtUserInfo) {
            hideLoading();
            CtUserInfo userInfo = (CtUserInfo) response.result;
            LoginInstance.getInstance().updateProfile(AppCoreRuntime.context, userInfo, false);
            mUserInfo = userInfo;
            refreshData();
        } else {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }

    }


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.BIND_ACCOUNT.equals(response.getApiName())) {
            handleBindAccountResult(response);
        } else if (ApiManager.UN_BIND_ACCOUNT.equals(response.getApiName())) {
            handleUnBindAccountResult(response);
        }
        return false;
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config=new CustomUiConfig();
        config.mTopbarStyle= CustomUiConfig.BarStyle.WHITE_STYLE;
        config.mTopbarMiddleAreaName=getString(R.string.social);
        config.mTopbarLeftAreaName=getString(R.string.back_icon);
        return config;
    }

    @Override
    protected void onStop() {
        super.onStop();
        thirdAccountProxy.onActivityStop();
    }
}
